<template>
  <el-dialog
    v-el-drag-dialog
    title="槽批单"
    :visible.sync="visible"
    width="1024px"
    @closed="reset"
  >
    <el-form ref="dataForm" class="form" :model="temp" :rules="rules" label-position="right" label-width="110px">
      <el-form-item label="责任机构">
        <el-input v-model="userInfo.orgName" disabled />
      </el-form-item>
      <el-form-item label-width="0">
        <el-input v-model="csmText" placeholder="请输入">
          <el-select slot="prepend" v-model="qtype" style="width: 100px;" placeholder="请选择">
            <el-option label="客户编号" value="csmCode" />
            <el-option label="客户电话" value="csmRgPhone" />
            <el-option label="客户名称" value="csmName" />
          </el-select>
        </el-input>
      </el-form-item>
      <el-form-item label-width="0">
        <div>
          <el-button slot="append" class="append-search" @click="search">查询</el-button>
          <el-button slot="append" class="append-search" @click="resetData">重置</el-button>
        </div>
      </el-form-item>

      <el-form-item label="客户">
        <el-input v-model="csmInfo.csmName" disabled />
      </el-form-item>
      <el-form-item label="电话" prop="csmPhone">
        <el-select v-model="temp.contactPhone">
          <el-option v-for="item in phoneList" :key="item.csmPhone" :value="item.csmPhone" :label="item.csmPhone" />
        </el-select>
      </el-form-item>
      <el-form-item label="地址" prop="csmAddress">
        <el-select v-model="temp.csmAddressId">
          <el-option v-for="item in csmAddressList" :key="item.csmAddressId" :value="item.csmAddressId" :label="item.csmAddress" />
        </el-select>
      </el-form-item>
      <el-form-item label="商品" prop="goodsObj">
        <el-select v-model="temp.goodsObj" value-key="goodsCode" :loading="$loadingPlugin.getGoodsList" filterable placeholder="请选择" @change="goodsChange">
          <el-option
            v-for="item in goodsList"
            :key="item.goodsCode"
            :label="item.goodsName"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="单价(元/吨)" prop="gPrice">
        <el-input v-model="temp.gPrice" @input="temp.gPrice=temp.gPrice.replace(/[^\d.]/g, '').replace(/^0\d+|^\./g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(.*\..{2}).*$/,'$1')" />
      </el-form-item>
      <el-form-item label="灌装费" prop="totalFee1">
        <el-input v-model="temp.totalFee1" @input="temp.totalFee1=temp.totalFee1.replace(/[^\d.]/g, '').replace(/^0\d+|^\./g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(.*\..{2}).*$/,'$1')" />
      </el-form-item>
      <el-form-item label="批发类型" prop="wsaleType">
        <el-select v-model="temp.wsaleType" placeholder="请选择">
          <el-option
            v-for="item in wsaleTypeBottleMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="空车重(吨)" prop="weight1">
        <el-input v-model="temp.weight1" placeholder="请输入" @input="temp.weight1=temp.weight1.replace(/[^\d.]/g, '').replace(/^0\d+|^\./g, '').replace(/\.{5,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(.*\..{5}).*$/,'$1')" />
      </el-form-item>
      <el-form-item label="重车重(吨)" prop="weight1">
        <el-input v-model="temp.weight2" placeholder="请输入" @input="temp.weight2=temp.weight2.replace(/[^\d.]/g, '').replace(/^0\d+|^\./g, '').replace(/\.{5,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(.*\..{5}).*$/,'$1')" />
      </el-form-item>
      <el-form-item label="实收净重(吨)" prop="totalNetWeight">
        <el-input v-model="temp.totalNetWeight" placeholder="请输入" @input="temp.totalNetWeight=temp.totalNetWeight.replace(/[^\d.]/g, '').replace(/^0\d+|^\./g, '').replace(/\.{5,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(.*\..{5}).*$/,'$1')" />
      </el-form-item>
      <el-form-item label="盈余量(吨)" prop="weight3">
        <el-input v-model="weight3" placeholder="请输入" disabled />
      </el-form-item>
      <el-form-item v-show="temp.wsaleType === 3" label="运输车辆" prop="truckNo">
        <el-select v-model="temp.truckNo" placeholder="请选择">
          <el-option
            v-for="item in truckList"
            :key="item.truckCode"
            :label="item.truckCode"
            :value="item.truckCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-show="temp.wsaleType === 3" label="运费" prop="decimalSpare1">
        <el-input v-model="temp.decimalSpare1" :max="100000" @input="temp.decimalSpare1=temp.decimalSpare1.replace(/[^\d.]/g, '').replace(/^0\d+|^\./g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(.*\..{2}).*$/,'$1')" />
      </el-form-item>
      <el-form-item label="备注" prop="remark" class="block">
        <el-input v-model="temp.remark" type="textarea" :rows="3" maxlength="255" show-word-limit />
      </el-form-item>
    </el-form>
    <h3>应收金额：{{ totalMoney }}</h3>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">
        取消
      </el-button>
      <el-button :loading="$loadingPlugin.success" type="primary" @click="success">
        确定
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { queryCsmInfo, queryTruckList, queryGoodsListLorrySale, querySelectGoodsPrice, saveLorryOrderDropIn } from '@/api'
  import { mapGetters } from 'vuex'
  import { accMul, keepDotLength } from '@/utils/math'

  export default {
    name: 'add-lorry-order',
    data() {
      return {
        visible: false,
        csmText: '',
        qtype: 'csmCode',
        csmInfo: {},
        phoneList: [],
        csmAddressList: [],
        truckList: [],
        selectGdProperty: '',
        selectGtFlag: '',
        selectGoodsWeight: 0,
        goodsList: [],
        wsaleTypeBottleMap: [{ 'value': 2, 'desc': '上门批发', 'key': 'TYPE2' }, { 'value': 3, 'desc': '代运业务', 'key': 'TYPE3' }],
        temp: {
          contactPhone: '',
          csmAddressId: '',
          gPrice: '0.00',
          totalFee1: '0.00',
          goodsObj: undefined,
          wsaleType: 3,
          weight1: '0.00000',
          weight2: '0.00000',
          totalNetWeight: '0.00000',
          truckNo: '',
          decimalSpare1: '0.00',
          remark: ''
        },
        rules: {
          gPrice: [{ required: true, message: '请输入单价', trigger: 'change' }],
          totalFee1: [{ required: true, message: '请输入灌装费', trigger: 'change' }],
          weight1: [{ required: true, message: '请输入空车重', trigger: 'change' }],
          weight2: [{ required: true, message: '请输入重车重', trigger: 'change' }],
          totalNetWeight: [{ required: true, message: '请输入实收净重', trigger: 'change' }],
          // weight3: [{ required: true, message: '请输入盈余量', trigger: 'change' }],
          wsaleType: [{ required: true, message: '请选择批发类型', trigger: 'change' }],
          decimalSpare1: [{ required: true, message: '请输入运费', trigger: 'change' }],
          goodsObj: [{ required: true, message: '请选择商品', trigger: 'change' }],
          truckNo: [{ required: true, message: '请选择运输车辆', trigger: 'change' }]
        }
      }
    },
    computed: {
      ...mapGetters([
        'orgList', 'userInfo'
      ]),
      totalMoney: function() {
        const value = keepDotLength(this.temp.gPrice, 2) * keepDotLength(this.temp.totalNetWeight, 2) + keepDotLength(this.temp.totalFee1, 2) + keepDotLength(this.temp.decimalSpare1, 2)
        return keepDotLength(value, 2).toFixed(2)
      },
      weight3: function() {
        const weigth3 = this.temp.weight2 - this.temp.weight1 - (keepDotLength(this.temp.totalNetWeight, 5)).toFixed(5)
        return keepDotLength(weigth3, 5).toFixed(5)
      }
    },
    methods: {
      async open() {
        await Promise.all([this.getTruckList()])
        return new Promise(resolve => {
          this.resolve = resolve
          this.visible = true
        })
      },
      // 商品列表
      async getGoodsList() {
        const res = await queryGoodsListLorrySale()
        console.log('res', res)
        var resultData = []
        if (res.data.length > 0) {
          for (var i = 0; i < res.data.length; i++) {
            if (res.data[i].pricingMode === 2) {
              resultData.push(res.data[i])
            }
          }
        }
        this.goodsList = resultData
      },
      // 查询配送车辆列表
      async getTruckList() {
        const res = await queryTruckList()
        console.log('运输车辆', res)
        this.truckList = res.data
      },
      // 查询
      async search() {
        if (!this.csmText) {
          this.$message.warning('查询条件不能为空!')
          return
        }
        const params = {
          csmStatus: 9, // 查询状态不是已注销的客户
          csmType: 16 // 瓶批客户
        }
        params[this.qtype] = this.csmText
        const res = await queryCsmInfo(params)
        if (!res.data) {
          this.$message.info('此用户不存在')
          return
        }
        if (res.data.csmType !== 16) {
          this.$message.info('此用户不是瓶批用户')
          return
        }
        this.csmInfo = res.data
        console.log('this.csmInfo', this.csmInfo)
        // 电话
        this.phoneList = this.csmInfo.phoneItems.filter(item => item.cpStatus === 2)
        if (this.phoneList.length) {
          this.temp.contactPhone = this.phoneList[0].csmPhone
        }
        // 地址
        this.csmAddressList = this.csmInfo.addressItems
        if (this.csmAddressList.length) {
          this.temp.csmAddressId = this.csmInfo.addressItems[0].csmAddressId
        }
        // 查询商品列表
        this.getGoodsList()
      },
      // 商品改变 查询商品价格
      async goodsChange(obj) {
        const goodsInfo = this.goodsList.find(item => item.goodsCode === obj.goodsCode)
        const res = await querySelectGoodsPrice({
          goodsCode: goodsInfo.goodsCode,
          orgSNNo: goodsInfo.orgSNNo,
          csmId: this.csmInfo.csmId,
          csmType: this.csmInfo.csmType
        })
        console.log('商品[', res)
        const unitId = res.data.unitId
        if (unitId === 2) {
          this.selectGdProperty = res.data.gdProperty
          this.selectGtFlag = res.data.gtFlag
          this.selectGoodsWeight = res.data.weight // 商品重量
          this.$set(this.temp, 'gPrice', accMul(res.data.basePrice, 1000)) // 单位转换成吨
        } else {
          this.$message.info('当前商品单位不对')
          return
        }
      },
      success() {
        this.$refs.dataForm.validate(valid => {
          if (!valid) return
          // 校验空车重 与重车重
          if (keepDotLength(this.temp.weight1 * 1000, 2) > keepDotLength(this.temp.weight2 * 1000, 2)) {
            this.$message.warning('输入的空车重大于重车重,不可提交')
            return
          }
          const matchAddress = this.csmAddressList.find(item => item.csmAddressId === this.temp.csmAddressId)
          const param = { // 定义保存数据
            orgId: this.csmInfo.orgId,
            orgName: this.csmInfo.orgName,
            orgSNNo: this.csmInfo.orgSNNo,
            csmId: this.csmInfo.csmId,
            csmName: this.csmInfo.csmName,
            csmCode: this.csmInfo.csmCode,
            contactPhone: this.temp.contactPhone,
            contact: this.temp.csmName,
            csmAddress: matchAddress.csmAddress,
            csmAddressId: matchAddress.csmAddressId,
            csmType: this.csmInfo.csmType,
            totalFee1: this.temp.totalFee1,
            weight1: keepDotLength(accMul(this.temp.weight1, 1000), 2).toFixed(2),
            weight2: keepDotLength(accMul(this.temp.weight2, 1000), 2).toFixed(2),
            totalNetWeight: keepDotLength(accMul(this.temp.totalNetWeight, 1000), 2).toFixed(2),
            weight3: keepDotLength(accMul(this.temp.weight3, 1000), 2).toFixed(2),
            wsaleFlag: 2,
            decimalSpare1: this.temp.decimalSpare1,
            wsaleType: this.temp.wsaleType,
            truckNo: this.temp.truckNo,
            remark: this.temp.remark
            // gPrice: this.temp.gPrice,
          }
          // 保存商品单价
          const orderWsaleOrderDetailInfoList = []
          const tReceivable = accMul(keepDotLength(this.temp.gPrice, 2), keepDotLength(this.temp.totalNetWeight, 5))
          console.log('this.temp.goodsObj', this.temp.goodsObj)
          const orderWsaleOrderDetailInfo = {
            gtId: this.temp.goodsObj.gtId, // 商品分类
            gtFlag: this.selectGtFlag, // 商品分类标识
            goodsId: this.temp.goodsObj.goodsId, // 商品id
            goodsCode: this.temp.goodsObj.goodsCode, // 商品编号
            goodsName: this.temp.goodsObj.goodsName, // 商品名称
            gdProperty: this.selectGdProperty, // 商品性质
            gdWeight: this.selectGoodsWeight, // 商品每瓶重量/千克
            gPrice: this.temp.gPrice, // 商品单价
            gCount: 1, // 商品数量
            netWeight: this.temp.totalNetWeight, // 总重量(吨)
            tReceivable: keepDotLength(tReceivable, 2).toFixed(2), // 总金额
            specCode: this.temp.goodsObj.specCode, // 规格型号编号
            specName: this.temp.goodsObj.specName, // 规格名称
            specAlias: this.temp.goodsObj.specAlias,
            pricingMode: this.temp.goodsObj.pricingMode // 计价方式
          }
          orderWsaleOrderDetailInfoList.push(orderWsaleOrderDetailInfo)
          param.orderWsaleOrderDetailInfoList = orderWsaleOrderDetailInfoList // 保存商品详细信息
          // 15KG液化气^100.00^1;
          param.goodsDesc = this.temp.goodsObj.goodsName + '^' + this.temp.gPrice + '^' + 1 // 保存商品描述
          const orderMoney = tReceivable + keepDotLength(param.decimalSpare1, 2) + keepDotLength(this.temp.totalFee1, 2)
          param.decimalSpare4 = keepDotLength(orderMoney, 2).toFixed(2) // 订单总额
          param.tReceivables = param.decimalSpare4 // 保存应收金额
          // 保存数据
          if (this.temp.wsaleType === 2) { // 上门批发
            this.$confirm('确认保存当前上门槽批单？', '提示', {
              type: 'warning'
            }).then(() => {
              const loading = this.$message({
                message: '正在执行操作',
                duration: 0,
                iconClass: 'el-icon-loading'
              })
              saveLorryOrderDropIn(param).then(() => {
                this.$notify({
                  title: '提示',
                  message: '保存成功',
                  type: 'success',
                  duration: 2000
                })
                this.visible = false
              }).finally(() => {
                loading.close()
              })
            })
          } else if (this.temp.wsaleType === 3) { // 代运业务
            this.$confirm('确认保存当前代运槽批单？', '提示', {
              type: 'warning'
            }).then(() => {
              const loading = this.$message({
                message: '正在执行操作',
                duration: 0,
                iconClass: 'el-icon-loading'
              })
              saveLorryOrderDropIn(param).then(() => {
                this.$notify({
                  title: '提示',
                  message: '保存成功',
                  type: 'success',
                  duration: 2000
                })
              }).finally(() => {
                loading.close()
              })
            })
          }
        })
      },
      // 重置
      resetData() {
        console.log('从之')
      },
      reset() {
        this.csmText = ''
        this.qtype = ''
        this.temp = {
          contactPhone: '',
          csmAddress: '',
          goodsId: '',
          gPrice: 0,
          totalFee1: 0,
          wsaleType: 3,
          weight1: 0,
          weight2: 0,
          totalNetWeight: 0,
          truckNo: '',
          decimalSpare1: 0,
          remark: ''
        }
        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate()
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  flex-wrap: wrap;
  & /deep/ .el-form-item {
    width: 33.3%;
    padding-right: 10px;
    .el-form-item__content > .el-select {
      width: 100%;
    }
  }
  .block {
    width: 100%;
  }
}
</style>
